<?php

namespace app\admin\controller\weixin\template;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;
use think\Cache;
use addons\weixin\library\WechatTemplateService;

/**
 * 微信模板
 *
 * @icon fa fa-circle-o
 */
class Wechat extends Backend
{

    /**
     * Wechat模型对象
     * @var \app\admin\model\weixin\template\Wechat
     */
    protected $model = null;
    protected $cacheTag = '_system_wechat';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\weixin\template\Wechat;

        $this->view->assign("defaultList",$this->model->getDefaultList());

        //得到所属行业
        $industry = Cache::tag($this->cacheTag)->remember('_wechat_industry', function () {
            try {
                $cache = WechatTemplateService::getIndustry();
                if (!$cache) {
                    return [];
                }
                Cache::tag($this->cacheTag, ['_wechat_industry']);
                return $cache->toArray();
            } catch (\Exception $e) {
                return $e->getMessage();
            }
        }, 0) ?: [];
        !is_array($industry) && $industry = [];
        $this->assign('industry', $industry);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams("fa_weixin_template.name,choice.name");

            $total = $this->model
                ->with(['choice'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['choice'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = method_exists($this, 'preExcludeFields') ? $this->preExcludeFields($params) : $params;

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    //如果用户选择默认推送模板，则强原来的默认修改掉 必须有一个为默认 如果都没有设置，默认第一个为默认

                    //获取默认数据id
                    $wxid = $params["wx_id"];
                    if(!$wxid){
                        $this->error("参数有误");
                    }
                    //如果没有默认，应该给当前数据默认
                    $minid = $this->model->where("wx_id=$wxid")->value("id");
                    //获取当前默认的数据
                    $defid = $this->model->where(["default"=>1,"wx_id"=>$wxid])->value("id");

                    //如果存在默认 当前提交数据又是默认，则修改为默认当前
                    if($defid){
                        if($params["default"] == 1) {
                            $this->model->where(["wx_id" => $wxid, "id" => $defid])->update(["default" => 0]); //修改之前默认的为非默认状态
                        }
                    }else{
                        //未有默认的情况 如果是第一次提交 就默认为默认 尽管没有勾选默认
                        if(!$minid){
                            $params["default"] = 1;
                        }
                    }



                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{

            $chatList = \app\admin\model\weixin\Weixin::field("wid,name")->select();

            $this->assign("chatList",$chatList);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = method_exists($this, 'preExcludeFields') ? $this->preExcludeFields($params) : $params;
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    //如果用户选择默认推送模板，则强原来的默认修改掉 必须有一个为默认 如果都没有设置，默认第一个为默认

                    //获取默认数据id
                    $wxid = $params["wx_id"];
                    if(!$wxid){
                        $this->error("参数有误");
                    }
                    //如果没有默认，应该给当前数据默认
                    $minid = $this->model->where("wx_id=$wxid")->value("id");
                    //获取当前默认的数据
                    $defid = $this->model->where(["default"=>1,"wx_id"=>$wxid])->value("id");


                    //判断当前数据情况
                    if($ids == $defid){
                        if($ids == $minid){
                            $params["default"] = 1;
                        }else{
                            if($params["default"] == 1) {
                                $this->model->where(["wx_id" => $wxid, "id" => $defid])->update(["default" => 0]); //修改之前默认的为非默认状态
                            }else{
                                $this->model->where(["wx_id" => $wxid, "id" => $minid])->update(["default" => 1]); //修改之前默认的为非默认状态
                            }
                        }

                    }else{ //修改的不是当前默认的数据
                        if($params["default"] == 1) {
                            $this->model->where(["wx_id" => $wxid, "id" => $defid])->update(["default" => 0]); //修改之前默认的为非默认状态
                        }
                    }


                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{
            $chatList = \app\admin\model\weixin\Weixin::field("wid,name")->select();
            $this->assign("chatList",$chatList);
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
